package edu.com.wjt219971332.controller;

import edu.com.wjt219971332.entity.Result;
import edu.com.wjt219971332.entity.User;
import edu.com.wjt219971332.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping("user")
public class userController {
    @Autowired
    private UserService UserService;
    @RequestMapping("show")
    public String show(){
        return "user/queryuser";
    }

    @GetMapping
    @ResponseBody
    public Result queryByPage(User user, @RequestParam("page") Integer page, @RequestParam("size")Integer size, @RequestParam(value = "sort", required = false)String sort) {
        PageRequest pageable = PageRequest.of(page-1, size);
        Page<User> result = this.UserService.queryByPage(user, pageable);
        return Result.ok("获取成功！",  result.getTotalElements(), result.get().collect(Collectors.toList()));
    }
    @RequestMapping("/select")
    @ResponseBody
    public Result select(@RequestParam("username") String username){
        return  Result.ok("操作成功！", this.UserService.queryByusername(username));
    }
    @RequestMapping("/updateInit/{userid}")
    public String updateInit(@PathVariable("userid") Integer userId
            , Model model){
        User user = UserService.queryById(userId);
        model.addAttribute("user", user);
        return  "user/update";
    }
    @RequestMapping("/update")
    @ResponseBody
    public ResponseEntity<Map<String, String>> update(@ModelAttribute("user") User user){
        Map<String, String> response = new HashMap<>();
//        return Result.ok("修改成功",this.UserService.update(user));
        UserService.update(user);
        response.put("message", "修改成功");
        return ResponseEntity.ok(response);
    }

    @RequestMapping("/deleteInit/{userid}")
    @ResponseBody
    public String deleteInit(@PathVariable("userid") Integer userId){
        UserService.deleteById(userId);
        return "redirect:/login/loginshow";
    }
}
